package com.anji.plus.ajpushlibrary;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;

import com.anji.plus.ajpushlibrary.http.AppSpPushRequestUrl;
import com.anji.plus.ajpushlibrary.hw.HWPushUtil;
import com.anji.plus.ajpushlibrary.model.AppSpModel;
import com.anji.plus.ajpushlibrary.model.NotificationMessageModel;
import com.anji.plus.ajpushlibrary.oppo.OppoPushUtil;
import com.anji.plus.ajpushlibrary.service.AppSpPushController;
import com.anji.plus.ajpushlibrary.service.IAppSpCallback;
import com.anji.plus.ajpushlibrary.util.BrandUtil;
import com.anji.plus.ajpushlibrary.util.PushInfoUtil;
import com.anji.plus.ajpushlibrary.vivo.VivoPushUtil;
import com.heytap.msp.push.callback.ICallBackResultService;
import com.vivo.push.PushClient;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * Copyright © 2018 anji-plus
 * 安吉加加信息技术有限公司
 * http://www.anji-plus.com
 * All rights reserved.
 * <p>
 * 1，入口类，初始化，获取接口回调
 * 2，单例
 * 3，为了集成的便携性和兼容性，SDK没有引入第三方jar包，
 * 所以可以看到，json的解析，也是采用的原始方式
 * 4，服务端校验数据完整性，加入sign参数，采用RSA加密方式，前端和后端约定公钥
 * </p>
 */
public final class AppSpPushConfig {

    private static volatile AppSpPushConfig appSpPushConfig;
    private Context context;
    public static String appKey;
    public static String secretKey;
    public static String requestUrl = "";//请求自家服务器的接口


    private ICallBackResultService mPushCallback = new ICallBackResultService() {
        @Override
        public void onRegister(int responseCode, final String registerID) {
            //注册的结果,如果注册成功,registerID就是客户端的唯一身份标识
            if (responseCode == 0) {
                AppSpPushConstant.pushToken = registerID;
                AppSpPushConstant.brandType = AppSpPushConstant.OPPO;
                AppSpPushLog.d("Oppo registerID ==》 " + registerID);
                AppSpPushConfig.getInstance().sendRegTokenToServer(new IAppSpCallback() {
                    @Override
                    public void pushInfo(AppSpModel<String> appSpModel) {
                        Log.i("注册成功", registerID + "---" + appSpModel.getRepData());
                    }

                    @Override
                    public void error(String code, String msg) {
                        Log.i("注册成功", registerID + "---" + msg);
                    }

                });
                AppSpPushLog.e("注册成功, registerId:" + registerID);
            } else {
                AppSpPushLog.e("注册失败," + "code=" + responseCode + ",msg=" + registerID);
            }
        }

        @Override
        public void onUnRegister(int code) {
            //反注册的结果
            if (code == 0) {
                AppSpPushLog.e("注销成功, code:" + code);
            } else {
                AppSpPushLog.e("注销失败, code:" + code);
            }
        }

        @Override
        public void onGetPushStatus(final int code, int status) {
            //获取当前的push状态返回,根据返回码判断当前的push状态
            if (code == 0 && status == 0) {
                AppSpPushLog.e("Push状态正常," + "code=" + code + ",status=" + status);
            } else {
                AppSpPushLog.e("Push状态错误," + "code=" + code + ",status=" + status);
            }
        }

        @Override
        public void onGetNotificationStatus(final int code, final int status) {
            //获取当前通知栏状态
            if (code == 0 && status == 0) {
                AppSpPushLog.e("通知状态正常," + "code=" + code + ",status=" + status);
            } else {
                AppSpPushLog.e("通知状态错误," + "code=" + code + ",status=" + status);
            }
        }

        @Override
        public void onSetPushTime(final int code, final String s) {
            //获取设置推送时间的执行结果
            AppSpPushLog.e("SetPushTime," + "code=" + code + ",result=" + s);
        }

    };

    private AppSpPushConfig() {
    }

    public static synchronized AppSpPushConfig getInstance() {
        if (appSpPushConfig == null) {
            appSpPushConfig = new AppSpPushConfig();
        }
        return appSpPushConfig;
    }

    /**
     * @param host 请求的基本地址
     */
    public AppSpPushConfig setHost(String host) {
        AppSpPushRequestUrl.Host = host;
        return appSpPushConfig;
    }

    /**
     * 设置是否打开debug开关
     *
     * @param debug true表示打开debug
     */
    public AppSpPushConfig setDebuggable(boolean debug) {
        AppSpPushLog.setDebugged(debug);
        return appSpPushConfig;
    }

    /**
     * 初始化
     *
     * @param context 可以是 activity/fragment/view
     * @param appKey  用于标识哪个APP，唯一标识
     * @param path    是用户自己公司的接口
     */
    public void init(Context context, String appKey, String secretKey, String path) {
        requestUrl = path;
        if (TextUtils.isEmpty(appKey)) {
            AppSpPushLog.e("appKey must be not Empty !");
            return;
        }
        if (TextUtils.isEmpty(path)) {
            AppSpPushLog.e("request host must be not Empty !");
            return;
        }
        if (TextUtils.isEmpty(secretKey)) {
            AppSpPushLog.e("appspSecretKey must be not Empty !");
            return;
        }
        this.context = context;
        this.appKey = appKey;
        this.secretKey = secretKey;

        //传递在各大平台注册后的信息到自家公司服务器
        pushInit();

    }

    /**
     * 根据手机品牌初始化推送
     */
    public void pushInit() {

        // 设置开启日志,发布时请关闭日志
        JPushInterface.setDebugMode(true);
        // 极光推送初始化
        JPushInterface.init(context);
        if (BrandUtil.getInstance(context).isHuawei()) {
            //获取token并发送给后端
            AppSpPushConstant.brandType = AppSpPushConstant.HW;
//            new HWPushUtil(context).getToken();
            new HWPushUtil(context).getToken();
        } else if (BrandUtil.getInstance(context).isXiaomi()) {
            // 注册push服务，注册成功后会向XMPushReceiver发送广播
            AppSpPushConstant.brandType = AppSpPushConstant.XM;
            if (shouldInit()) {
                MiPushClient.registerPush(context, AppSpPushConstant.xmAppId, AppSpPushConstant.xmAppKey);
            }
        } else if (BrandUtil.getInstance(context).isOPPO()) {
            AppSpPushConstant.brandType = AppSpPushConstant.OPPO;
            try {
                OppoPushUtil oppoPushUtil = new OppoPushUtil(context);
                oppoPushUtil.init();
                if (oppoPushUtil.isSupportPush()) {
                    oppoPushUtil.register(mPushCallback);//setPushCallback接口也可设置callback
                    oppoPushUtil.requestNotificationPermission();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (BrandUtil.getInstance(context).isVIVO()) {
            AppSpPushConstant.brandType = AppSpPushConstant.VIVO;
            PushClient.getInstance(context).initialize();
            new VivoPushUtil(context).bind();
        } else {
            AppSpPushConstant.brandType = AppSpPushConstant.OTHER;
        }

    }

    //初始化推送服务
    private boolean shouldInit() {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = context.getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    //点击通知栏后获取信息
    public NotificationMessageModel getNotifyMessage(Intent intent) {
        //获取数据
        if (BrandUtil.getInstance(context).isHuawei()) {
            return PushInfoUtil.getHWIntentData(intent);
        } else if (BrandUtil.getInstance(context).isXiaomi()) {
            return PushInfoUtil.getXMIntentData(intent);
        } else if (BrandUtil.getInstance(context).isVIVO()) {
            return PushInfoUtil.getVivoIntentData(intent);
        } else if (BrandUtil.getInstance(context).isOPPO()) {
            return PushInfoUtil.getOppoIntentData(intent);
        } else {
            return PushInfoUtil.getJPushIntentData(intent);
        }
    }

    /**
     * push注册成功后将数据传给服务器
     *
     * @param iAppSpCallback
     */
    public void sendRegTokenToServer(IAppSpCallback iAppSpCallback) {
        AppSpPushController appSpController = new AppSpPushController(context, appKey);
        appSpController.putPushInfo(iAppSpCallback);
    }

}
